package _interview75;

import _object.TreeNode;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;

/**
 * 1161. 最大层内元素和
 */
public class No1161 {
    private List<Integer> list;
    private int maxDeep;

    /**
     * 1. 深度优先遍历
     */
    public int maxLevelSum1(TreeNode root) {
        list = new ArrayList<>();

        int ans = 0;
        int maxSum = Integer.MIN_VALUE;

        dfs(root, 0);
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i) > maxSum) {
                ans = i + 1;
                maxSum = list.get(i);
            }
        }
        return ans;
    }

    private void dfs(TreeNode node, int deep) {
        if (node == null) return;
        if (list.size() == deep) list.add(node.val);
        else list.set(deep, list.get(deep) + node.val);
        maxDeep = Math.max(deep + 1, maxDeep);
        dfs(node.left, deep + 1);
        dfs(node.right, deep + 1);
    }

    /**
     * 2. 广度优先遍历
     */
    public int maxLevelSum2(TreeNode root) {
        Queue<TreeNode> queue = new ArrayDeque<>();
        queue.add(root);

        int ans = 0;
        int maxSum = Integer.MIN_VALUE;

        for (int layer = 1; !queue.isEmpty(); layer++) {
            int curSum = 0;
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode poll = queue.poll();
                if (poll.left != null) queue.offer(poll.left);
                if (poll.right != null) queue.offer(poll.right);
                curSum += poll.val;
            }
            if (curSum > maxSum) {
                maxSum = curSum;
                ans = layer;
            }
        }
        return ans;
    }
}
